package projcet.test.student.tencennews;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import com.google.gson.Gson;
import com.squareup.okhttp.Request;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.ArrayList;
import java.util.List;

import fr.arnaudguyon.xmltojsonlib.XmlToJson;

public class MainActivity extends AppCompatActivity {

    ListView lv_show;
    List<Info.RssBean.ChannelBean.ItemBean> list = new ArrayList<>();
    MyAdapter myAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);


        getNews();
        lv_show = findViewById(R.id.lv_show);
        lv_show.setDividerHeight(10);

        myAdapter = new MyAdapter(list, this);
        lv_show.setAdapter(myAdapter);

        lv_show.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(MainActivity.this, DetailActivity.class);
                intent.putExtra("url", list.get(position).getLink());
                startActivity(intent);
            }
        });
    }


    /**
     * 获取新闻
     */
    private void getNews() {
        list.clear();
        String url = "http://news.qq.com/newsgn/rss_newsgn.xml";
        OkHttpUtils
                .get()
                .url(url)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Request request, Exception e) {
                        Log.d("MainActivity", request.toString());
                    }

                    @Override
                    public void onResponse(String response) {
                        /**
                         * 解析刷新并存储
                         */
                        Log.d("MainActivity", response);
                        XmlToJson xmlToJson = new XmlToJson.Builder(response).build();
                        String jsonString = xmlToJson.toString();
                        Log.d("MainActivity", jsonString);
                        jsonString = jsonString.replace("\\", "");
                        Log.d("MainActivity", "__________________" + jsonString);
                        Gson gson = new Gson();
                        Info info = gson.fromJson(jsonString, Info.class);
                        list.addAll(info.getRss().getChannel().getItem());
                        myAdapter.notifyDataSetChanged();
                    }
                });
    }
}
